package com.ruoyi.lvlian.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.UrDecoderlUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.Kaifangqian;
import com.ruoyi.lvlian.dto.ContractInfoDto1;
import com.ruoyi.lvlian.dto.WarehouseInfoDto;
import com.ruoyi.lvlian.dto.WarehouseInfoSignDto;
import com.ruoyi.lvlian.service.ICommonService;
import com.ruoyi.lvlian.service.IDriverInfoService;
import com.ruoyi.lvlian.service.IKaifangqianService;
import com.ruoyi.lvlian.util.JsonFileReaderUtil;
import com.ruoyi.lvlian.util.OrderNumberGenerator;
import com.ruoyi.lvlian.vo.PaymentInfoVo;
import com.ruoyi.lvlian.vo.WarehouseInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.lvlian.domain.WarehouseInfo;
import com.ruoyi.lvlian.service.IWarehouseInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 入库单Controller
 *
 * @author liyuxi
 * @date 2024-07-19
 */
@RestController
@RequestMapping("/warehouseInfo")
@Api(value = "物流信息", tags = "销售物流采购物流")
public class WarehouseInfoController extends BaseController {
    @Autowired
    private IWarehouseInfoService warehouseInfoService;

    @Autowired
    private IDriverInfoService driverInfoService;

    @Autowired
    private ICommonService iCommonService;
    @Autowired
    private IKaifangqianService kaifangqianService;

    /**
     * 查询入库单列表
     */
    @ApiOperation("查询入库单列表")
//    //@RequiresPermissions("inWarehouseInfo:inWarehouseInfo:list")
    @GetMapping("/list")
    public TableDataInfo list(WarehouseInfoDto inWarehouseInfo) {
        if (SecurityUtils.getUserId() == 1) {
            inWarehouseInfo.setOrgCodes(new ArrayList<>(Arrays.asList("50000000")));
        } else {
            List<String> orgCodes = iCommonService.queryCurrentOrgCode(SecurityUtils.getUserId());
            if (orgCodes.size() == 0) {
                return getDataTable(new ArrayList<WarehouseInfoVo>());
            }
            if (Objects.isNull(inWarehouseInfo.getOrgCodes()) || inWarehouseInfo.getOrgCodes().isEmpty()) {
                orgCodes.removeIf(code -> code.length() != 8);
                inWarehouseInfo.setOrgCodes(orgCodes);
            }

        }

        if (StringUtils.isNotEmpty(inWarehouseInfo.getPlateNo())) {
            inWarehouseInfo.setPlateNo(UrDecoderlUtil.decodeIfEncoded(inWarehouseInfo.getPlateNo()));
        }

        if (StringUtils.isNotEmpty(inWarehouseInfo.getInvoiceNum())) {
            if (StringUtils.isEmpty(inWarehouseInfo.getBuyerName())) {
                return new TableDataInfo();
            }

        }


        startPage();
        List<WarehouseInfoVo> list = warehouseInfoService.selectWarehouseInfoList(inWarehouseInfo);
        return getDataTable(list);
    }


    @ApiOperation("获取入库单详细信息")
    @GetMapping("/getInfoById")
    public AjaxResult getInfoById(@ApiParam(value = "入库单ID", required = true) @RequestParam(value = "id") String id) {
        return success(warehouseInfoService.selectWarehouseInfoById(id));
    }

    @ApiOperation("根据条件查物流信息")
    @GetMapping("/getInfoByOther")
    public AjaxResult getInfoByOther(@ApiParam(value = "采购物流结算/销售物流结算", required = true) @RequestParam(value = "category") String category,
                                     @ApiParam(value = "入库单号/销售方出库单号", required = true) @RequestParam(value = "warehouseNum") String warehouseNum,
                                     @ApiParam(value = "车牌号码", required = true) @RequestParam(value = "plateNo") String plateNo
    ) {
        return success(warehouseInfoService.getInfoByOther(category, warehouseNum, plateNo));
    }

    private String validateInData(WarehouseInfo po) {
        if (StringUtils.isEmpty(po.getInNum())) {
            return "入库单号不能为空";
        }

        return "success";
    }

    /**
     * 修改入库单
     */
    @ApiOperation("新增入库单  修改入库单 一体")
    //@RequiresPermissions("inWarehouseInfo:inWarehouseInfo:edit")
    @Log(title = "入库单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated WarehouseInfo inWarehouseInfo) {

        if (!"success".equalsIgnoreCase(validateInData(inWarehouseInfo))) {
            return error(validateInData(inWarehouseInfo));
        }
        try {

            return toAjax(warehouseInfoService.updateWarehouseInfo(inWarehouseInfo));
        } catch (Exception e) {
            e.printStackTrace();
            return error("保存报错");
        }

    }

    /**
     * 删除入库单
     */

    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody String[] ids) {
        return toAjax(warehouseInfoService.deleteWarehouseInfoByIds(ids));


    }


    @ApiOperation("导入采购物流结算")
    @PostMapping("/importInfoBuyer")
    public AjaxResult importInfoBuyer(MultipartFile file) {
        // 获取到批量导入的数据集合
        List<WarehouseInfo> dtoList = null;
        List<WarehouseInfo> newList = new ArrayList<>();
        try {
            dtoList = warehouseInfoService.importInfo(file, "采购物流结算", 3);
            for (WarehouseInfo po : dtoList) {
                if (StringUtils.isEmpty(po.getInDate()) & StringUtils.isNotEmpty(po.getOutDate())) {
                    po.setInDate(po.getOutDate());
                }
                po.setCategory("采购物流结算");
                newList.add(po);
            }
            warehouseInfoService.bachSave(newList);
            driverInfoService.flushDriverVehicleRef();
        } catch (Exception e) {
            e.printStackTrace();
            return success("模板错误");
        }


        int total = dtoList.size();
        int totalFail = total - newList.size();
        String msg = "解析到" + total + "条数据，" + "导入成功" + newList.size() + "条，导入失败" + totalFail + "条！";
        return success(msg);
    }


    @ApiOperation("导入销售物流结算结算")
    @PostMapping("/importInfo")
    public AjaxResult importInfo(MultipartFile file) {
        // 获取到批量导入的数据集合
        List<WarehouseInfo> dtoList = null;
        List<WarehouseInfo> newList = new ArrayList<>();
        try {
            dtoList = warehouseInfoService.importInfo(file, "销售物流结算", 3);
            for (WarehouseInfo po : dtoList) {
                if (StringUtils.isEmpty(po.getOrgCode()) || StringUtils.isEmpty(po.getInNum()) || StringUtils.isEmpty(po.getSellerName()) || StringUtils.isEmpty(po.getBuyerName()) ||
                        StringUtils.isEmpty(po.getPlateNo()) || StringUtils.isEmpty(po.getDriverName())) {
                    continue;
                }

                if (StringUtils.isEmpty(po.getInDate()) & StringUtils.isNotEmpty(po.getOutDate())) {
                    po.setInDate(po.getOutDate());
                }

                if (StringUtils.isEmpty(po.getBuyerContractNum()) & StringUtils.isNotEmpty(po.getSellerContractNum())) {
                    po.setBuyerContractNum(po.getSellerContractNum());
                }

                po.setCategory("销售物流结算");
                newList.add(po);
            }
            warehouseInfoService.bachSave(newList);
            int result = driverInfoService.flushDriverVehicleRef();
        } catch (Exception e) {
            e.printStackTrace();
            return success("模板错误");
        }

        int total = dtoList.size();
        int totalFail = total - newList.size();
        String msg = "解析到" + total + "条数据，" + "导入成功" + newList.size() + "条，导入失败" + totalFail + "条！";
        return success(msg);
    }


    @Autowired
    private JsonFileReaderUtil jsonReader;

    @ApiOperation("发起签署")
    @PostMapping("/draft")
    public String createDraftContract(@RequestBody @Validated WarehouseInfoSignDto dto) {
        String url = "http://121.40.250.100/resrun-paas/kaifangqian/openAPI/V2/contract/draft";

        if(StringUtils.isEmpty( dto.getSellerPhone())){
            return "销售方手机号码不能为空";
        }
        if(StringUtils.isEmpty( dto.getBuyerName())){
            return "购买方名称不能为空";
        }



        String jsonName="taitongcaigou.json";
        if( dto.getBuyerName().contains("河南漯湾")){
            jsonName= "luowancaigou.json" ;
        }
        System.out.println("================================"+jsonName);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 1. 读取JSON文件内容
            // 测试场景2：解析JSON为Jackson的JsonNode对象（通用解析）
            JsonNode jsonNode = jsonReader.readJsonFile(jsonName, JsonNode.class);


            // 获取signTemplateParamList数组的第一个元素（因为它是数组）
            JsonNode signTemplateParam = jsonNode.get("signTemplateParamList").get(0);

            // 获取templateParamList数组
            JsonNode templateParamList = signTemplateParam.get("templateParamList");
            if (templateParamList.isArray()) {
                // 转换为ArrayNode以便添加新元素
                ArrayNode arrayNode = (ArrayNode) templateParamList;
                ObjectMapper mapper = new ObjectMapper();

                ObjectNode inNum = mapper.createObjectNode();
                inNum.put("paramKey", "inNum");
                inNum.put("paramValue", dto.getInNum());
                arrayNode.add(inNum);

                ObjectNode buyerWeighDate = mapper.createObjectNode();
                buyerWeighDate.put("paramKey", "buyerWeighDate");
                buyerWeighDate.put("paramValue", dto.getBuyerWeighDate());
                arrayNode.add(buyerWeighDate);

                ObjectNode plateNo = mapper.createObjectNode();
                plateNo.put("paramKey", "plateNo");
                plateNo.put("paramValue", dto.getPlateNo());
                arrayNode.add(plateNo);


                ObjectNode buyerGoodsName = mapper.createObjectNode();
                buyerGoodsName.put("paramKey", "buyerGoodsName");
                buyerGoodsName.put("paramValue", dto.getBuyerGoodsName());
                arrayNode.add(buyerGoodsName);

                ObjectNode buyerPhone = mapper.createObjectNode();
                buyerPhone.put("paramKey", "buyerPhone");
                buyerPhone.put("paramValue", dto.getBuyerPhone());
                arrayNode.add(buyerPhone);


                ObjectNode driverName = mapper.createObjectNode();
                driverName.put("paramKey", "driverName");
                driverName.put("paramValue", dto.getDriverName());
                arrayNode.add(driverName);

                ObjectNode driverPhone = mapper.createObjectNode();
                driverPhone.put("paramKey", "driverPhone");
                driverPhone.put("paramValue", dto.getDriverPhone());
                arrayNode.add(driverPhone);


                ObjectNode buyerTareWeight = mapper.createObjectNode();
                buyerTareWeight.put("paramKey", "buyerTareWeight");
                buyerTareWeight.put("paramValue", dto.getBuyerTareWeight());
                arrayNode.add(buyerTareWeight);

                ObjectNode buyerGrossWeight = mapper.createObjectNode();
                buyerGrossWeight.put("paramKey", "buyerGrossWeight");
                buyerGrossWeight.put("paramValue", dto.getBuyerGrossWeight());
                arrayNode.add(buyerGrossWeight);


                // 创建要添加的新参数对象
                ObjectNode buyerNetWeight = mapper.createObjectNode();
                buyerNetWeight.put("paramKey", "buyerNetWeight");
                buyerNetWeight.put("paramValue", dto.getBuyerNetWeight());
                arrayNode.add(buyerNetWeight);


       /*         ObjectNode buyerNetWeight = mapper.createObjectNode();
                buyerNetWeight.put("paramKey", "buyerNetWeight");
                buyerNetWeight.put("paramValue", dto.getBuyerNetWeight());
                arrayNode.add(buyerNetWeight);*/


                ObjectNode buyerDeductWeight = mapper.createObjectNode();
                buyerDeductWeight.put("paramKey", "buyerDeductWeight");
                buyerDeductWeight.put("paramValue", dto.getBuyerDeductWeight());
                arrayNode.add(buyerDeductWeight);


                ObjectNode buyerGoodsUnit = mapper.createObjectNode();
                buyerGoodsUnit.put("paramKey", "buyerGoodsUnit");
                buyerGoodsUnit.put("paramValue", dto.getBuyerGoodsUnit());
                arrayNode.add(buyerGoodsUnit);


                ObjectNode sellerPhone = mapper.createObjectNode();
                sellerPhone.put("paramKey", "sellerPhone");
                sellerPhone.put("paramValue", dto.getSellerPhone());
                arrayNode.add(sellerPhone);

                ObjectNode sellerName = mapper.createObjectNode();
                sellerName.put("paramKey", "sellerName");
                sellerName.put("paramValue", dto.getSellerName());
                arrayNode.add(sellerName);
            }


            // 修改receiver信息
            JsonNode receiverNode = jsonNode.path("signerList").get(0).path("receiver");
            if (receiverNode.isObject()) {
                ObjectNode receiver = (ObjectNode) receiverNode;
                receiver.put("name", dto.getSellerName());
                receiver.put("contact", dto.getSellerPhone());
            }


            System.out.println("\n=== JSON文件内容（解析为JsonNode）===");
            System.out.println(jsonNode.toPrettyString());

            // 2. 创建POST请求
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/json; charset=UTF-8");  // Add charset here
            post.setHeader("Accept", "application/json");
//防止乱码产生

            StringEntity entity = new StringEntity(jsonNode.toString(), StandardCharsets.UTF_8);
            post.setEntity(entity);


            // 3. 执行请求并获取响应
            HttpResponse response = httpClient.execute(post);
            String responseBody = EntityUtils.toString(response.getEntity());

            System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
            System.out.println("Response: " + responseBody);

            return responseBody;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error occurred: " + e.getMessage();
        }
    }

    @ApiOperation("获取合同短链接")
    @GetMapping("/pageUrl")
    public String getContractPageUrl(
            @RequestParam(required = true) @ApiParam(value = "生成的合同id是开放签生成的", required = true, example = "ff808081975dc9950197c0731bb905d5") String contractId,
            @RequestParam(required = true) @ApiParam(value = "token", required = true, example = "W89FUDDR") String appAuthToken,
            @RequestParam(required = true) @ApiParam(value = "签署环节中传购买方的甲方的电话", required = true, example = "13791273388") String contact,
            @RequestParam(required = true) @ApiParam(value = "物流的id", required = true) String warehouseInfoId) {

        appAuthToken = "EE7TJN1E";

//保存签章信息
        Kaifangqian kaifangqian = new Kaifangqian();
        kaifangqian.setUniqueCode(OrderNumberGenerator.generateOrderNumber());
        kaifangqian.setContractId(contractId);
        kaifangqian.setAppAuthToken(appAuthToken);
        kaifangqian.setContact(contact);
        kaifangqian.setContractNum(warehouseInfoId);
        kaifangqian.setCreateUser(SecurityUtils.getUsername());
        kaifangqian.setCreateDate(DateUtils.getCurrentTime());
        kaifangqian.setId( warehouseInfoId);
        kaifangqianService.insertKaifangqian(kaifangqian);

        // Build the URL with parameters
        String url = "http://121.40.250.100/resrun-paas/kaifangqian/openAPI/V2/contract/pageUrl?uniqueCode=" + kaifangqian.getUniqueCode() + "&appAuthToken=" + appAuthToken + "&contractId=" + contractId + "&taskId&contact=" + contact + "&partyName&noLogin=1&pageUrlExpireTime";
        System.out.println("请求链接  === " + url);


        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // Create GET request
            HttpGet get = new HttpGet(url);
            System.out.println(url);
            // Add headers (similar to your draft method)
            get.setHeader("Content-Type", "application/json; charset=UTF-8");  // Add charset here


            get.setHeader("Accept", "application/json");
            get.setHeader("sign", ""); // Add your sign header here

            // Execute request
            HttpResponse response = httpClient.execute(get);
            String responseBody = EntityUtils.toString(response.getEntity());

            System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
            System.out.println("Response: " + responseBody);

            return responseBody;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error occurred: " + e.getMessage();
        }
    }


    @GetMapping("/downloadBuyerwarehouseInfoById")
    public AjaxResult downloadBuyerwarehouseInfoById(
            @RequestParam(required = true) @ApiParam(value = "根据物流id来查看签章页面", required = true) String warehouseInfoId) throws IOException {

        // 生成唯一标识符
        Kaifangqian kaifang = kaifangqianService.queryKaifangqianByContractNum(warehouseInfoId);
        // 构建带参数的URL
        String url = String.format("http://121.40.250.100/resrun-paas/kaifangqian/openAPI/V2/contract/document/download" +
                        "?appAuthToken=%s" +
                        "&uniqueCode=%s" +
                        "&contact=%s" +
                        "&contractId=%s",
                kaifang.getAppAuthToken(), kaifang.getUniqueCode(), kaifang.getContact(), kaifang.getContractId());
        return success(url);
    }

    @ApiOperation("回调方法")
    @PostMapping("/receiveResult")
    public String receiveResult() {


   /*     // 2. 验证签名
        if (!verifySignature(notification)) {
            throw new SecurityException("Invalid signature");
        }

        // 3. 处理业务逻辑
        processNotification(notification);*/

        // 4. 返回success
        return "success";
    }

    //https://data.lvlianhengsheng.com/dev-api/lvlian/contractInfo/callback
    @ApiOperation("get回调方法")
    @GetMapping("/callback")
    public ApiResponse callback() {
        ApiResponse response = new ApiResponse();
        response.setCode("200");
        response.setMessage("Success");
        return response;
    }

    public class ApiResponse {
        private String code;
        private String message;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
}
